'''Mount dspace as a proxied wsgi app
   Use paste.proxy
'''
import os
import paste.urlmap
import paste.proxy
from webob import Request, Response
from apkn.portal.users import User, Base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Session = sessionmaker()

HERE = os.path.dirname(__file__)

SCHEMA_SEARCH_PATH = "pas,public"

def make_app(*args, **kw):
	app = paste.urlmap.URLMap()
	

	dest = kw['dest']
	db_uri = kw['db_uri']

	class MyProxy(object):
		def __init__(self, dest, db_uri):
		   self.proxy = paste.proxy.Proxy(dest)
		   #connection to the database
		   engine = create_engine(db_uri)
		   Session.configure(bind=engine)	
		   
		   # get a handle on the metadata
		   metadata = Base.metadata
		   metadata.create_all(engine)		   	    
		
		def get_user_email(self,userid):
		
        # get a handle on the user object			
			users_table = User.__table__
			session = Session()
			#set search path to pas schema
			search_path_query = "SET search_path TO %s;" %(SCHEMA_SEARCH_PATH)
			set_search_path = session.execute(search_path_query)
			users = session.query(User).filter(User.username==userid)
			user = users.all()
			session.close()
			if len(user) !=1:
				return None	    
			return user[0].email						

		
		def __call__(self, environ, start_response):
			req = Request(environ)
			user_id = None
			user_email = None
			identity = environ.get('repoze.who.identity')
			if identity is not None:
				user_id = identity.get('repoze.who.userid')
			if user_id is not None:
				user_email = self.get_user_email(user_id)
				
			if user_email is not None:
				req.headers['REMOTE_USER'] = user_email
			else:
				req.headers['REMOTE_USER'] = ''

			#modify language headers so that dspace picks users language
			cookie_dict = req.cookies
			if cookie_dict.has_key('I18N_LANGUAGE'):
				if req.headers.has_key('ACCEPT_LANGUAGE'):
					lang = cookie_dict['I18N_LANGUAGE']
					aclang = req.headers['ACCEPT_LANGUAGE']
					req.headers['ACCEPT_LANGUAGE'] = lang + ',' + aclang

			res = req.get_response(self.proxy)
			res.decode_content()

			return res(environ, start_response)

	app[kw['dspace_node']] = MyProxy(dest,db_uri)
	return app
	

